﻿using Microsoft.VisualStudio.Modeling;
using System;
using System.Text;

namespace Project.Co_DataTransformationPrototype
{
    class RenameMapping : MappingBase
    {

        public RenameMapping(EventContext eventContext)
        {
            this.eventContext = eventContext;
            //generateSQLCodeMapping();
        }

        internal override void generateSQLCodeMapping(StringBuilder existingScript = null)
        {
            strSQLMapping = new StringBuilder();

            if (existingScript != null)
                strSQLMapping.Append(existingScript);

            if (typeof(Entity).Equals(eventContext.elementEventArgs.ModelElement.GetType()))
                renameTableSQLCode();
            else if (typeof(EntityAttribute).Equals(eventContext.elementEventArgs.ModelElement.GetType()))
                renameColumnSQLCode();

            strSQLMapping.AppendLine("GO" + Environment.NewLine);
        }

        private void renameTableSQLCode()
        {
            ElementPropertyChangedEventArgs eArgs = (ElementPropertyChangedEventArgs)eventContext.elementEventArgs;
            strSQLMapping.AppendFormat("EXEC sp_RENAME '{0}.{1}', '{2}' " + Environment.NewLine, Data.DatabaseSettings.SHEMA_NAME, eArgs.OldValue, eArgs.NewValue);
        }

        private void renameColumnSQLCode()
        {
            Entity parentEntity;
            EntityAttribute attribute = eventContext.elementEventArgs.ModelElement as EntityAttribute;
            ElementPropertyChangedEventArgs eArgs = (ElementPropertyChangedEventArgs)eventContext.elementEventArgs;
            
            if (attribute.IsDeleted)
                parentEntity = attribute.ParentEntity;
            else
                parentEntity = attribute.Entity;

            strSQLMapping.AppendFormat("EXEC sp_RENAME '{0}.{1}.{2}', '{3}', 'COLUMN' " + Environment.NewLine, Data.DatabaseSettings.SHEMA_NAME, parentEntity.CurrentName, eArgs.OldValue, eArgs.NewValue);
        }

        /// 1. Drop foreign keys in A
        /// 2. Drop foreign keys of type A
        /// 3. Rename table
        /// 4. Create foreign keys in A
        /// 5. Create foreign keys of type A

        /// --- mySQL
        /// Alter TABLE oldName RENAME newName
        /// RENAME TABLE oldName to newName

        /// --- SQL server
        /// use dbase
        /// GO
        /// sp_RENAME oldName, newName
        /// GO

        /// --- Plain
        /// CREATE TABLE newName (column datatype, *);
        /// INSERT INTO newName SELECT * FROM oldName
    }
}
